package com.subang.function.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.OptionalDouble;
import javax.servlet.http.HttpServletResponse;

import com.subang.common.constant.HttpStatus;
import com.subang.common.utils.bean.BeanUtils;
import com.subang.function.domain.SbEvaluation;
import com.subang.function.service.ISbEvaluationService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.subang.common.annotation.Log;
import com.subang.common.core.controller.BaseController;
import com.subang.common.core.domain.AjaxResult;
import com.subang.common.enums.BusinessType;
import com.subang.function.domain.SbTeacher;
import com.subang.function.service.ISbTeacherService;
import com.subang.common.utils.poi.ExcelUtil;
import com.subang.common.core.page.TableDataInfo;

/**
 * 讲师Controller
 * 
 * @author subei
 * @date 2025-03-13
 */
@RestController
@RequestMapping("/function/teacher")
public class SbTeacherController extends BaseController
{
    @Autowired
    private ISbTeacherService sbTeacherService;

    @Autowired
    private ISbEvaluationService sbEvaluationService;

    /**
     * 查询讲师列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SbTeacher sbTeacher)
    {
        startPage();
        List<SbTeacher> list = sbTeacherService.selectSbTeacherList(sbTeacher);
        List<SbTeacher> teacherDtos = new ArrayList<>();
        for (SbTeacher teacher : list) {
            List<SbEvaluation> evaluations = sbEvaluationService.selectGkEvaluationByTeacherId(teacher.getTeacherId());
            SbTeacher teacherDto = new SbTeacher();
            BeanUtils.copyProperties(teacher, teacherDto);
            // 计算平均分
            OptionalDouble averageScore = evaluations.stream()
                    .mapToDouble(SbEvaluation::getScore)
                    .average();
            // 检查是否有评价分数可以计算平均分（避免除以零的情况）
            if (averageScore.isPresent()) {
                double avg = averageScore.getAsDouble();
                String formattedAvg = String.format("%.2f", avg); // 格式化为两位小数
                teacherDto.setEvaluationScore(formattedAvg);
            } else {
                // 如果没有评价，可以设置平均分为0或其他默认值
                teacherDto.setEvaluationScore(String.valueOf(0.00));
            }
            teacherDto.setEvaluations(evaluations);
            teacherDto.setEvaluationNumber(evaluations.size());
            teacherDtos.add(teacherDto);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(teacherDtos);
        rspData.setTotal(getDataTable(list).getTotal());
        return rspData;
    }

    /**
     * 导出讲师列表
     */
    @PreAuthorize("@ss.hasPermi('function:teacher:export')")
    @Log(title = "讲师", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SbTeacher sbTeacher)
    {
        List<SbTeacher> list = sbTeacherService.selectSbTeacherList(sbTeacher);
        ExcelUtil<SbTeacher> util = new ExcelUtil<SbTeacher>(SbTeacher.class);
        util.exportExcel(response, list, "讲师数据");
    }

    /**
     * 获取讲师详细信息
     */
    @PreAuthorize("@ss.hasPermi('function:teacher:query')")
    @GetMapping(value = "/{teacherId}")
    public AjaxResult getInfo(@PathVariable("teacherId") Long teacherId)
    {
        return success(sbTeacherService.selectSbTeacherByTeacherId(teacherId));
    }

    /**
     * 新增讲师
     */
    @PreAuthorize("@ss.hasPermi('function:teacher:add')")
    @Log(title = "讲师", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbTeacher sbTeacher)
    {
        return toAjax(sbTeacherService.insertSbTeacher(sbTeacher));
    }

    /**
     * 修改讲师
     */
    @PreAuthorize("@ss.hasPermi('function:teacher:edit')")
    @Log(title = "讲师", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbTeacher sbTeacher)
    {
        return toAjax(sbTeacherService.updateSbTeacher(sbTeacher));
    }

    /**
     * 删除讲师
     */
    @PreAuthorize("@ss.hasPermi('function:teacher:remove')")
    @Log(title = "讲师", businessType = BusinessType.DELETE)
	@DeleteMapping("/{teacherIds}")
    public AjaxResult remove(@PathVariable Long[] teacherIds)
    {
        return toAjax(sbTeacherService.deleteSbTeacherByTeacherIds(teacherIds));
    }
}
